import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { GoodsService } from '@core/routes-services/goods.service';
import { AgentLevelService } from '@core/routes-services/agent-level.service';
import { Step1Component } from '../step/step1.component';
import { Step2Component } from '../step/step2.component';
import { Step3Component } from '../step/step3.component';

@Component({
  selector: 'app-goods-edit',
  templateUrl: './goods-edit.component.html',
  styles: [`
    :host ::ng-deep .upload-list-inline .ant-upload-list-item {
      float: left;
      width: 160px;
      margin-right: 8px;
    }
  `],
})
export class GoodsEditComponent implements OnInit {
  id: any = 0;// 默认表示新增
  entity: any = {};
  isLoading: boolean = false;
  levelOptions: any [] = [];
  goodsPricesOptions: any [] = [];
  imgList: any[] = [];

  @ViewChild('step0') step0: Step1Component;
  @ViewChild('step1') step1: Step2Component;
  @ViewChild('step2') step2: Step3Component;

  title: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    public goodsService: GoodsService,
    private agentLevelService: AgentLevelService,
    public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.goodsService.reset();
    this.goodsService.entity = this.entity;
    this.title = this.entity.title;
    this.route.queryParams.forEach((params: Params) => {
      this.id = +params['id'];
      this.initLevelOptions();
    });
  }

  indexChange(index) {
    this.goodsService.step = index;
  }

  initLevelOptions() {
    this.isLoading = true;
    if (this.id == 0) {//新增 获取等级
      this.agentLevelService.getAll().then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.levelOptions = res.data.agentLevelsList;
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    } else {// 修改 获取entity，levelOptions 等相关信息一并在获取entity接口中返回了
      this.initEntity();
    }
  }

  initEntity() {
    this.isLoading = true;
    this.goodsService.detail(this.id).then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.entity = res.data.goods;
        this.title = this.entity.title;
        this.goodsService.entity = this.entity;
        this.levelOptions = res.data.agentLevels;
        this.goodsPricesOptions = res.data.goodsPrices;
        this.imgList = res.data.goodsImages;
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });

  }

}
